﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using com.loto.Common.DBUtility;
using com.huigo.Framework.Model;

namespace com.huigo.Framework.BLL
{
    public class CustFeeFlow
    {
        public static bool TradeNoIsExisted(string tradeNo)
        {
            Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
            feeFlow.FlowPayNo = tradeNo;
            List<string> fields = new List<string>() 
             {  
                "FLOW_CUST_FID",
             };
            if (SqlServerDal.CustFeeFlow.GetItem(feeFlow, fields, null, null) == null)
                return false;
            else
                return SqlServerDal.CustFeeFlow.GetItem(feeFlow, fields, null, null).FlowCustFid > 0;
        }
        public static bool InsertFeeFLow(long idCustFid,long userID, string refShowId, long idRefId, decimal PayFee
,SqlTransaction tran)
        {
            Model.CustFeeFlow feeFlow = new com.huigo.Framework.Model.CustFeeFlow();
            Model.CustInfo custinfo = CustInfo.GetCustInfoByCustId(idCustFid);
            feeFlow.FlowCustFid = idCustFid;
            feeFlow.FlowType = (int)Dict.FeeType.REFUND;
            feeFlow.FlowUserFid = userID;
            feeFlow.FlowRelatedFid = idRefId;
            feeFlow.FlowChannel = Dict.PayType.BALANCE.ToString();
            feeFlow.FlowCreatedOn=DateTime.Now;
            feeFlow.FlowBeforeFee = custinfo.CustUsefulFee;
            feeFlow.FlowChangeFee = PayFee;
            feeFlow.FlowOutPayNo = refShowId;
            feeFlow.FlowAfterFee = custinfo.CustUsefulFee + PayFee;
            feeFlow.FlowMemo =  "退款：" + refShowId;
            feeFlow.FlowCreditedOn = DateTime.Now;
            feeFlow.FlowFlag = 1;
            return SqlServerDal.CustFeeFlow.Insert(feeFlow, tran);
        }
        /// <summary>
        /// 查询消费明细
        /// </summary>
        /// <param name="custFid"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public static List<Model.CustFeeFlow> GetCustFeeFlow(long custFid,DateTime startTime,DateTime endTime,int type, int PageSize, int PageIndex)
        {
            List<string> fileds = new List<string>()
            {
                "FLOW_ID,FLOW_CUST_FID,FLOW_TYPE,FLOW_FOR,FLOW_USER_FID,FLOW_RELATED_FID,FLOW_CHANNEL,FLOW_CREATED_ON,FLOW_BEFORE_FEE,FLOW_CHANGE_FEE,FLOW_AFTER_FEE,FLOW_MEMO,FLOW_CREDITED_ON,FLOW_OUT_PAY_NO,FLOW_PAY_NO"
            };
            List<WhereStatement> whereList = new List<WhereStatement>();
            if (startTime != DateTime.MinValue && endTime != DateTime.MinValue)
            {
                whereList.Add(new WhereStatement("FLOW_CREATED_ON", "BETWEEN", "'" + startTime + "' AND '" + endTime + "'", "AND"));
            }
            if (type > 0)
            {
                if (type == 2)
                {
                    whereList.Add(new WhereStatement("FLOW_TYPE", "in", "(2,3,5)", "and"));
                }
                if (type == 3)
                {
                    whereList.Add(new WhereStatement("FLOW_TYPE", "in", "(1,4,6,7)", "and"));
                }
            }
            whereList.Add(new WhereStatement("FLOW_CUST_FID","=",""+custFid+"","and"));
            whereList.Add(new WhereStatement("FLOW_FLAG","=","1",""));

            List<OrderByStatement> orderList = new List<OrderByStatement>()
            {
                new OrderByStatement("FLOW_CREATED_ON",false)
            };

            List<Model.CustFeeFlow> flowList = null;
            int recordCount = 0;
            int pageCount = 0;
            flowList = SqlServerDal.CustFeeFlow.GetItemsByProc(fileds, null, whereList, orderList, "[PROC_PAGINATION_OUT]", PageSize, PageIndex, out recordCount, out pageCount, null);
            flowList.ForEach(delegate(Model.CustFeeFlow info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return flowList;
        }

        /// <summary>
        /// 充值列表查询
        /// </summary>
        /// <param name="custName">经销商</param>
        /// <param name="channel">支付方式</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="payNo">支付交易号</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static List<Model.CustFeeFlow> GetCustFeeFlowPayList(string custName, string channel, DateTime start, DateTime end, string payNo, int pageSize, int pageIndex)
        {
            List<string> fileds = new List<string>()
            {
                @"[FLOW_ID]
              ,[FLOW_CUST_FID]
              ,[FLOW_TYPE]
              ,[FLOW_FOR]
              ,[FLOW_USER_FID]
              ,[FLOW_RELATED_FID]
              ,[FLOW_CHANNEL]
              ,[FLOW_CREATED_ON]
              ,[FLOW_BEFORE_FEE]
              ,[FLOW_CHANGE_FEE]
              ,[FLOW_AFTER_FEE]
              ,[FLOW_MEMO]
              ,[FLOW_CREDITED_ON]
              ,[FLOW_OUT_PAY_NO]
              ,[FLOW_PAY_NO]
              ,[FLOW_FLAG],CUST_NAME"
            };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement ("left","HG_CUST_INFO","CUST_ID=FLOW_CUST_FID")
            };
            List<WhereStatement> whereList = new List<WhereStatement>();
            if (!string.IsNullOrEmpty(custName))
            {
                whereList.Add(new WhereStatement("CUST_NAME", "like", "'%" + custName + "%'", "and"));
            }
            if (start != DateTime.MinValue && end.AddDays(-1) != DateTime.MinValue)
            {
                whereList.Add(new WhereStatement("FLOW_CREATED_ON", "between", "'" + start + "' AND '" + end + "'", "AND"));
            }
            if (!string.IsNullOrEmpty(channel))
            {
                whereList.Add(new WhereStatement("FLOW_CHANNEL", "=", "'" + channel + "'", "and"));
            }
            if (!string.IsNullOrEmpty(payNo))
            {
                whereList.Add(new WhereStatement("FLOW_PAY_NO", "=", "'" + payNo + "'", "and"));
            }
            if (string.IsNullOrEmpty(custName) && start == DateTime.MinValue && end.AddDays(-1) == DateTime.MinValue && string.IsNullOrEmpty(channel) && string.IsNullOrEmpty(payNo))
            {
                whereList.Add(new WhereStatement("FLOW_CREATED_ON", "between", "'" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "' AND '" + DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd") + "'", "AND"));
            }
            whereList.Add(new WhereStatement("FLOW_TYPE", "=", "" + ((int)Dict.FeeType.SUPPLEMENT).ToString() + "", ""));

            List<OrderByStatement> orderList = new List<OrderByStatement>()
            {
                new OrderByStatement("FLOW_CREATED_ON",false)
            };

            List<Model.CustFeeFlow> CustFeeFlowInfo = null;
            int recordCount = 0;
            int pageCount = 0;
            CustFeeFlowInfo = SqlServerDal.CustFeeFlow.GetItemsByProc(fileds, joinList, whereList, orderList, "[PROC_PAGINATION_OUT]", pageSize, pageIndex, out recordCount, out pageCount, null);
            CustFeeFlowInfo.ForEach(delegate(Model.CustFeeFlow info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return CustFeeFlowInfo;
        }


        /// <summary>
        /// 消费流列表查询
        /// </summary>
        /// <param name="custName">经销商</param>
        /// <param name="orderNO">订单号</param>
        /// <param name="flowType">消费类型</param>
        /// <param name="orderStatus">订单类型</param>
        /// <param name="start">时间</param>
        /// <param name="end">时间</param>
        /// <param name="payNo">支付交易号</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static List<Model.CustFeeFlow> GetCustFeeFlowInfoList(string custName, string orderNO, int flowType, int orderStatus, DateTime start, DateTime end, string payNo, int pageSize, int pageIndex)
        {
    
            string WHERE = " 1=1";
            List<WhereStatement> whereList = new List<WhereStatement>();
            if (!string.IsNullOrEmpty(orderNO) && orderStatus > 0)
            {
                WHERE += " AND ORDER_NO = '" + orderNO + "' AND  ORDER_INS_TYPE_FID=" + orderStatus;
            }
            if (string.IsNullOrEmpty(orderNO) && orderStatus > 0)
            {
                WHERE += "  AND  ORDER_INS_TYPE_FID=" + orderStatus;
            }
            if (!string.IsNullOrEmpty(custName))
            {
                WHERE += " AND CUST_NAME LIKE '" + custName + "'";
               // whereList.Add(new WhereStatement("ORDER_NO", "=", "'" + orderNO + "'", "and"));
            }
            if (start != DateTime.MinValue && end.AddDays(-1) != DateTime.MinValue)
            {
                WHERE += " AND FLOW_CREATED_ON between '" + start + "' AND '" + end + "'";
               // whereList.Add(new WhereStatement("FLOW_CREATED_ON", "between", "'" + start + "' AND '" + end + "'", "AND"));
            }
            if (flowType > 0)
            {
                WHERE += " AND FLOW_TYPE=" + flowType;
               // whereList.Add(new WhereStatement("FLOW_TYPE", "=", "" + flowType.ToString() + "", "and"));
            }
            if (!string.IsNullOrEmpty(payNo))
            {
                WHERE += " AND FLOW_PAY_NO='" + payNo + "'";
                //whereList.Add(new WhereStatement("FLOW_PAY_NO", "=", "'" + payNo + "'", "and"));
            }
            if (string.IsNullOrEmpty(custName) && start == DateTime.MinValue && end.AddDays(-1) == DateTime.MinValue && flowType <= 0 && string.IsNullOrEmpty(payNo) && string.IsNullOrEmpty(orderNO) && orderStatus<= 0)
            {
                WHERE += " AND FLOW_CREATED_ON between '" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "' AND '" + DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd") + "'";
                //whereList.Add(new WhereStatement("FLOW_CREATED_ON", "between", "'" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "' AND '" + DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd") + "'", "AND"));
            }

            List<OrderByStatement> orderList = new List<OrderByStatement>()
            {
                new OrderByStatement("FLOW_CREATED_ON",false)
            };
            string sql = @" SELECT  DISTINCT(FLOW_ID) FLOW_ID
              ,[FLOW_CUST_FID]
              ,[FLOW_TYPE]
              ,[FLOW_FOR]
              ,[FLOW_USER_FID]
              ,[FLOW_RELATED_FID]
              ,[FLOW_CHANNEL]
              ,[FLOW_CREATED_ON]
              ,[FLOW_BEFORE_FEE]
              ,[FLOW_CHANGE_FEE]
              ,[FLOW_AFTER_FEE]
              ,[FLOW_MEMO]
              ,[FLOW_CREDITED_ON]
              ,[FLOW_OUT_PAY_NO]
              ,[FLOW_PAY_NO]
              ,[FLOW_FLAG],CUST_NAME FROM HG_CUST_FEE_FLOW LEFT JOIN HG_CUST_INFO ON CUST_ID=FLOW_CUST_FID LEFT JOIN HG_ORDER_INFO ON ORDER_CUST_FID=FLOW_CUST_FID WHERE "+WHERE;
            List<Model.CustFeeFlow> CustFeeFlowInfo = null;
            int recordCount = 0;
            int pageCount = 0;
            CustFeeFlowInfo = SqlServerDal.CustFeeFlow.GetItemsByProcTemp(sql, orderList, "[proc_pagination_out_union]", pageSize, pageIndex, out recordCount, out pageCount, null);
            CustFeeFlowInfo.ForEach(delegate(Model.CustFeeFlow info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return CustFeeFlowInfo;
        }

        public static bool InsertPayFeeFLow(long idCustFid, long userID, string payNo, string meno, decimal PayFee,string channel)
        {
            Model.CustFeeFlow feeFlow = new com.huigo.Framework.Model.CustFeeFlow();
            Model.CustInfo custinfo = CustInfo.GetCustInfoByCustId(idCustFid);
            feeFlow.FlowCustFid = idCustFid;
            feeFlow.FlowType = (int)Dict.FeeType.SUPPLEMENT;
            feeFlow.FlowUserFid = userID;
            feeFlow.FlowRelatedFid = 0;
            feeFlow.FlowChannel = channel;
            feeFlow.FlowCreatedOn = DateTime.Now;
            feeFlow.FlowBeforeFee = custinfo.CustUsefulFee;
            feeFlow.FlowChangeFee = PayFee;
            feeFlow.FlowPayNo = payNo;
            feeFlow.FlowOutPayNo = payNo;
            feeFlow.FlowAfterFee = custinfo.CustUsefulFee + PayFee;
            feeFlow.FlowMemo = meno;
            feeFlow.FlowCreditedOn = DateTime.Now;
            feeFlow.FlowFlag = 1;

            using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
            {
                try
                {
                    SqlServerDal.CustFeeFlow.Insert(feeFlow, trans);
                    BLL.CustInfo.updateFee(idCustFid, PayFee, trans);
                    trans.Commit();
                    return true;
                }
                catch
                {
                    trans.Rollback();
                    return false;
                }

            }
        }
    }
}
